using System;
using System.Linq;
using System.Collections.Generic;

namespace RestUpMVC.BlogService.Domain
{
    public class Post
    {
        private static readonly Dictionary<Guid, List<Post>> _posts = new Dictionary<Guid, List<Post>>();

        public Guid Id { get; set; }
        public string Content { get; set; }
        public DateTime Created { get; set; }
        public DateTime Updated { get; set; }

        public static ItemPage<Post> GetByBlog(Blog blog, int start, int limit)
        {
            if (blog == null) throw new ArgumentNullException("blog");

            var posts = _posts
                .Where(p => p.Key.Equals(blog.Id))
                .Select(p => p.Value).SingleOrDefault();

            var page = new ItemPage<Post>()
                           {
                               Start = start,
                               Limit = limit
                           };
            if (null != posts)
            {
                page.Items = posts.ToArray();
                page.Total = posts.Count;
                
            }
            return page;
        }

        public static void Create(Blog blog, ref Post post)
        {
            if (blog == null) throw new ArgumentNullException("blog");
            if (post == null) throw new ArgumentNullException("post");

            if (blog.Id.Equals(Guid.Empty))
            {
                throw new ArgumentException("The blog has an invalid Id.", "Id");
            }

            if (!_posts.Keys.Contains(blog.Id))
            {
                _posts.Add(blog.Id, new List<Post>());
            }

            var postsForBlog = _posts.Where(x => x.Key.Equals(blog.Id)).First().Value;

            var newId = Guid.NewGuid();
            while (postsForBlog.Any(x=>x.Id.Equals(newId)))
            {
                newId = Guid.NewGuid();
            }

            post.Created = DateTime.Now;
            post.Id = newId;
            postsForBlog.Add(post);
        }

        public static void Delete(Blog blog, Post post)
        {
            var posts = _posts.Where(x => x.Key.Equals(blog.Id)).FirstOrDefault().Value;
            if (null==posts)
            {
                return;
            }
            posts.Remove(post);
        }
    }
}